let api = require('./api')
let userLevel = require('./user-level')
let navigator = require('./xnavigator')
let queryparser = require('./queryparser')
let pddService = weex.requireModule('pddService')
let taobaoAuth = require('./taobao-auth')
let modal = weex.requireModule('modal')
module.exports = {
  goToBuy (id, listener) {
    return api.commissionItem.goToBuyParam({id: id}, null, listener).done(rs => {
      rs = rs.data
      switch (rs.ecomPlat) {
        case 'TAOBAO':
        case 'TMALL':
          if (!rs.data.specialId) {
            // 要去进行淘宝授权
            taobaoAuth.auth().done((data) => {
              if (data.authOk) {
                this.goToBuy(id, listener)
              }
            })
            return
          }
          let aliTradeService = weex.requireModule('aliTradeService')
          aliTradeService.couponPage({
            url: rs.data.clickUrl,
            adzoneId: rs.data.adzoneId,
            unionId: rs.data.unionId,
            pid: rs.data.pid,
            openType: 'native'
          })
          break
        case 'JD':
          if (weex.isRegisteredModule('keplerApi')) {
            let keplerApi = weex.requireModule('keplerApi')
            keplerApi.openPage({
              url: rs.data
            })
          }
          break
        case 'PDD':
          let params = queryparser(rs.data.mobileUrl)
          pddService.pullUp(params.launch_url, flag => {
            if (!flag) {
              let utils = weex.requireModule('utils')
              utils.openURL(rs.data.mobileShortUrl)
            }
          })
      }
    })
  },
  share (id, plat) {
    userLevel.checkPlus().done(rs => {
      if (plat === 'TMALL' || plat === 'TAOBAO') {
        api.user.taobaoRelationId().done(rs => {
          let data = rs.data
          if (data) {
            navigator.push('commission-item-share.js?id=' + id)
          } else {
            // 要去进行淘宝授权
            taobaoAuth.auth().done((data) => {
              if (data.authOk) {
                this.share(id)
              } else {
                modal.alert({message: '淘宝授权失败，无法进行分享！'})
              }
            })
          }
        })
      } else {
        navigator.push('commission-item-share.js?id=' + id)
      }
    })
  }
}
